package org.benxiong.iplay.ui;

import java.io.File;

import org.benxiong.iplay.R;
import org.benxiong.iplay.http.request.RequestFactory;
import org.benxiong.iplay.util.Constants;
import org.benxiong.iplay.util.GlobalVar;
import org.benxiong.iplay.util.ImageUtil;
import org.benxiong.iplay.util.LogX;
import org.benxiong.iplay.util.PreferencesUtil;
import org.benxiong.iplay.util.RegExpValidator;
import org.benxiong.iplay.util.ServerUtilities;
import org.benxiong.iplay.util.ToastUtil;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.google.android.gcm.GCMRegistrar;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class RegisterActivity extends BaseActivity {
	/**
	 * A dummy authentication store containing known user names and passwords.
	 * TODO: remove after connecting to a real authentication system.
	 */
	private static final String[]	DUMMY_CREDENTIALS	= new String[] {
														"foo@example.com:hello", "bar@example.com:world" };

	/**
	 * The default email to populate the email field with.
	 */
	public static final String		EXTRA_EMAIL			= "com.example.android.authenticatordemo.extra.EMAIL";

	// Values for email and password at the time of the login attempt.
	private String					mEmail;
	private String					mUsername;
	private String					mPassword;

	// UI references.
	private EditText				mEmailView;
	private EditText				mUsernameView;
	private EditText				mPasswordView;
	private ImageView				avatorImg;
	private Bitmap					mBitmap;

	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);

		getActionBar().setHomeButtonEnabled(false);
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		setContentView(R.layout.register);

		mEmailView = (EditText) findViewById(R.id.email);
		mUsernameView = (EditText) findViewById(R.id.username);
		mPasswordView = (EditText) findViewById(R.id.password);

		findViewById(R.id.join).setOnClickListener(this);
		avatorImg = (ImageView) findViewById(R.id.avator);
		avatorImg.setOnClickListener(this);
	}

	@Override
	public void onMessage(Message msg) {

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}

	@Override
	public void handleClick(int buttonId) {
		switch (buttonId) {
		case R.id.join:
			attemptRegister();
			break;
		case R.id.avator:
			Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
			getImage.addCategory(Intent.CATEGORY_OPENABLE);
			getImage.setType("image/jpeg");
			startActivityForResult(getImage, 0);
			break;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == 0) {
			// handle picture chosen action
			try {
				Uri selectedImage = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };

				Cursor cursor = getContentResolver().query(selectedImage,
						filePathColumn, null, null, null);
				cursor.moveToFirst();

				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String picturePath = cursor.getString(columnIndex);
				cursor.close();

				File file = new File(picturePath);
				mBitmap = ImageUtil.getBitmapFromFile(file, ImageUtil.AVATOR_WIDTH,
						ImageUtil.AVATOR_HEIGHT);// BitmapFactory.decodeFile(picturePath);
				avatorImg.setImageBitmap(mBitmap);

				// save bitmap to local avator folder
				ImageUtil.saveToLocal(file);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	/**
	 * Attempts to register the account specified by the login form. If there
	 * are form errors (invalid email, missing fields, etc.), the errors are
	 * presented and no actual login attempt is made.
	 */
	public void attemptRegister() {
		// Reset errors.
		mUsernameView.setError(null);
		mEmailView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mEmail = mEmailView.getText().toString();
		mPassword = mPasswordView.getText().toString();
		mUsername = mUsernameView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// check user name
		if (TextUtils.isEmpty(mUsername)) {
			mUsernameView.setError(getString(R.string.error_field_required));
			focusView = mUsernameView;
			cancel = true;
		} else if (mUsername.length() < 4) {
			mUsernameView.setError(getString(R.string.error_invalid_password));
			focusView = mUsernameView;
			cancel = true;
		}

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < 6) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mEmail)) {
			mEmailView.setError(getString(R.string.error_field_required));
			focusView = mEmailView;
			cancel = true;
		} else if (!RegExpValidator.isEmail(mEmail)) {
			mEmailView.setError(getString(R.string.email_format_incorrect));
			focusView = mEmailView;
			cancel = true;
		}

		// check avator not null
		if (mBitmap == null) {
			ToastUtil.toast(R.string.missing_avator);
			cancel = true;
			focusView = avatorImg;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			if (GlobalVar.tokenId == null) {
				ToastUtil.toast(R.string.regId_not_exists);
			} else {
				// BasePackage pack = new RegisterPack(mUsername, mPassword,
				// mEmail, GlobalVar.tokenId);
				// ConnectionManager.getInstance().sendPack(pack);
				showLoading(R.string.progress_registing);

				AsyncHttpClient client = new AsyncHttpClient();
				RequestParams rParam = new RequestParams();
				rParam.put("username", mUsername);
				rParam.put("password", mPassword);
				rParam.put("email", mEmail);
				rParam.put("tokenId", GlobalVar.tokenId);

				client.post(RequestFactory.URL_REGISTER, rParam, new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String response) {
						LogX.print(response);
						mProgressDialog.dismiss();
						try {
							JSONObject json = new JSONObject(response);
							String code = json.getString("code");
							if ("OK".equalsIgnoreCase(code)) {
								// register success
								PreferencesUtil.saveLoginInfo(mUsername, mPassword);
								setResult(1);
								// TODO: show update profile activity
							} else if ("DUPLICATED".equalsIgnoreCase(code)) {
								// user name already registered
								ToastUtil.toast(R.string.device_token_duplicated);
							} else if ("USERNAME_INVALID".equalsIgnoreCase(code)) {
								// user name already registered
								ToastUtil.toast(R.string.username_invalid);
							} else if ("PASSWORD_INVALID".equalsIgnoreCase(code)) {
								// user name already registered
								ToastUtil.toast(R.string.password_invalid);
							} else if ("EMAIL_INVALID".equalsIgnoreCase(code)) {
								// user name already registered
								ToastUtil.toast(R.string.email_invalid);
							} else if ("USERNAME_NOT_AVAILABLE".equalsIgnoreCase(code)) {
								// user name already registered
								ToastUtil.toast(R.string.username_not_available);
							} else {
								ToastUtil.toast("Register Failed: " + code);
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}

					@Override
					public void onFailure(Throwable arg0) {
						// TODO Auto-generated method stub
						super.onFailure(arg0);
						LogX.print("onFailure: " + arg0.getMessage());
						mProgressDialog.cancel();
					}

				});

			}
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		// GCM message registration
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);

		new AsyncTask() {

			@Override
			protected Object doInBackground(Object... params) {
				final String regId = GCMRegistrar.getRegistrationId(RegisterActivity.this);
				if (regId.equals("")) {
					LogX.print("start to register===");
					GCMRegistrar.register(RegisterActivity.this, Constants.GCM_SENDER_ID);
				} else {
					LogX.print("Already registered===" + regId);
					GlobalVar.tokenId = regId;
					if (!PreferencesUtil.isGCMRegSuccess()) {
						ServerUtilities.register(RegisterActivity.this, regId);
					}
				}
				return null;
			}

		}.execute();
	}
}
